package framework.common;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 単一センサを表すクラス。
 * @author uehara
 *
 */
public class SingleSensor extends Sensor {
	private Map<String,Object> map;

	public SingleSensor() {
		map = new HashMap<String,Object>();
	}

	@Override
	public SensorResponse sense(SensorRequest req) {
		SensorResponse res = new SensorResponse();
		switch (req.getCommand()) {
		case SensorRequest.GET:
			String attr = req.getAttribute();
			Object value = getAttribute(attr);
			res.setAttribute(attr);
			res.setValue(value);
			res.setResult(SensorResponse.OK);
			break;
		case SensorRequest.SET:
			attr = req.getAttribute();
			value = req.getValue();
			setAttribute(attr, value);
			res.setAttribute(attr);
			res.setValue(value);
			res.setResult(SensorResponse.OK);
			break;
		case SensorRequest.DIR:
			attr = req.getAttribute();
			Set<String> names = new HashSet<String>();
			for (String a : getAttributes()) {
				names.add(a);
			}
			res.setAttribute(attr);
			res.setValue(names);
			res.setResult(SensorResponse.OK);
			break;
		default:
			res.setAttribute("reason");
			res.setValue("undefined command");
			res.setResult(SensorResponse.ERR);
			break;
		}
		return res;
	}

	@Override
	public Set<String> getAttributes() {
		return map.keySet();
	}

	@Override
	public Object getAttribute(String attr) {
		return map.get(attr);
	}

	@Override
	public void setAttribute(String attr, Object value) {
		map.put(attr,  value);
	}

}
